/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.application;

import cn.easyplatform.contexts.ListContext;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.Record;
import cn.easyplatform.engine.runtime.datalist.DataListUtils;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.GetFieldsRequestMessage;
import cn.easyplatform.messages.response.FieldsUpdateResponseMessage;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GetFieldsCmd extends AbstractCommand<GetFieldsRequestMessage> {

	/**
	 * @param req
	 */
	public GetFieldsCmd(GetFieldsRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		WorkflowContext ctx = cc.getWorkflowContext();
		RecordContext rc = null;
		if (Strings.isBlank(req.getListId()))
			rc = ctx.getRecord();
		else {
			ListContext lc = ctx.getList(req.getListId());
			if (lc == null)
				return MessageUtils.dataListNotFound(req.getListId());
			rc = lc.getRecord(req.getKeys());
			if (rc == null && lc.getType().equals(Constants.CATALOG)) {
				Record record = DataListUtils.getRecord(cc, lc, req.getKeys());
				rc = lc.createRecord(req.getKeys(), record);
				rc.setParameter("815", false);
				rc.setParameter("814", "R");
				lc.appendRecord(rc);
			}
			if (rc == null)
				return MessageUtils.recordNotFound(lc.getBean().getTable(),
						Lang.concat(req.getKeys()).toString());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		for (String name : req.getBody())
			map.put(name, rc.getValue(name));
		return new FieldsUpdateResponseMessage(map);
	}

}
